package com.ruoyi.app.business.code;

import com.ruoyi.app.config.util.UserUtil;
import com.ruoyi.app.domain.user.inviteCode.InviteCode;
import com.ruoyi.app.domain.user.inviteCode.InviteCodeParam;
import com.ruoyi.common.core.enums.YesNoEnum;
import com.ruoyi.common.core.utils.CommonUtils;
import com.ruoyi.service.code.entity.InviteCodeEntity;
import com.ruoyi.service.code.service.InviteCodeService;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 作用：验证码服务
 * </p>
 *
 * @author Zane
 * @since 2025-10-03 22:01
 */
@Slf4j
@Component
public class InviteCodeBusiness {

  @Resource
  private InviteCodeService inviteCodeService;

  /**
   * 创建邀请码
   *
   * @param inviteCodeParam 邀请码参数
   * @return 邀请码
   */
  public InviteCode createInviteCode(InviteCodeParam inviteCodeParam) {
    String inviteCode = randomInviteCode();
    final Long userId = UserUtil.getUserId();
    LocalDateTime now = LocalDateTime.now();
    InviteCodeEntity inviteCodeEntity = new InviteCodeEntity()
        .setName(inviteCodeParam.getName())
        .setPostName(inviteCodeParam.getPost())
        .setInviteCode(inviteCode)
        .setCreateBy(userId)
        .setCreateTime(now)
        .setUpdateBy(userId)
        .setUpdateTime(now);
    inviteCodeService.save(inviteCodeEntity);
    return new InviteCode().setInviteCode(inviteCode)
        .setName(inviteCodeParam.getName())
        .setPost(inviteCodeParam.getPost());
  }

  /**
   * 核验邀请码
   */
  public void checkInviteCode(String inviteCode) {
    CommonUtils.requireNotNull(inviteCodeService.getByInviteCode(inviteCode), "邀请码无效");
  }

  public void useInviteCode(String inviteCode, Long laborId) {
    final InviteCodeEntity entity = CommonUtils.requireNotNull(
        inviteCodeService.getByInviteCode(inviteCode), "邀请码已被使用");
    entity.setLaborId(laborId)
        .setCheckedFlag(YesNoEnum.YES.getCode())
        .setUseTime(LocalDateTime.now())
        .setUpdateBy(laborId)
        .setUpdateTime(LocalDateTime.now());;
    this.inviteCodeService.updateById(entity);
  }

  private String randomInviteCode() {
    //邀请码源
    final String CODE_SOURCE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    final ThreadLocalRandom random = ThreadLocalRandom.current(); // 高效的随机数生成器
    final StringBuilder sb = new StringBuilder(14); // 预分配容量（12字符 + 2个分隔符）
    for (int i = 0; i < 12; i++) {
      // 随机选取字符集中的字符
      int index = random.nextInt(CODE_SOURCE.length());
      sb.append(CODE_SOURCE.charAt(index));
      // 每4个字符后插入分隔符（第4、8个字符后）
      if (i == 3 || i == 7) {
        sb.append('-');
      }
    }
    return sb.toString();
  }

  public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();
    final InviteCodeBusiness inviteCodeBusiness = new InviteCodeBusiness();
    for (int i = 0; i < 100000; i++) {
      String inviteCode = inviteCodeBusiness.randomInviteCode();
      if (map.containsKey(inviteCode)) {
        throw new RuntimeException("生成重复的邀请码");
      }
      map.put(inviteCode, "1");
      System.out.println(inviteCode);
    }
  }
}
